<!--
* description: 整车销售---订单收款---收款详情
* author:xlc
* createdDate: 2020-11-17
-->
<template>
  <div class="app-container app-container-table">
    <el-dialog
      v-dialogDrag
      style="margin:15px"
      :visible="popupsVisible"
      :title="titleName"
      center
      width="90%"
      :append-to-body="true"
      :close-on-click-modal="false"
      @close="closeEdit"
    >
      <dialogHeader slot="title" :title="titleName" :style-type="$store.state.app.dialogType" />
      <div style="margin:1rem">
        <!-- 表单组件 -->
        <one-table-template
          :key="shuaxin"
          ref="multipleTable1"
          :dynamic-buttons="tableButtons"
          :dynamic-components="tableComponents"
          :dynamic-api-config="apiConfig"
          :dynamic-form-fields="formField"
          :dynamic-is-show-more-btn="true"
          :dynamic-table-defult-height="150"
          :callback-obj="callbackObj"
        />
        <el-dialog
          v-dialogDrag
          :visible="showCodediv"
          center
          width="31%"
          :append-to-body="true"
          :close-on-click-modal="false"
          @close="closeCode"
        >
          <dialogHeader slot="title" title="收款信息" :style-type="$store.state.app.dialogType" />
          <div
            id="qrcode"
            ref="qrcode"
          />
        </el-dialog>
        <p class="filter-container filter-title">订单流水</p>
        <one-table-template
          ref="multipleTable"
          :dynamic-table-cols="tableCols"
          :dynamic-is-show-select="false"
          :dynamic-is-show-more-btn="true"
          :dynamic-table-defult-height="300"
          :callback-obj="callbackObj"
          :isshow-search-table-button="false"
        />
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import { orgApis } from '@/api/vesalesapi.js'
import OneTableTemplate from '@/components/templates/oneTable'
import QRCode from 'qrcodejs2'
import dialogHeader from '@/components/dialogHeader'
import Vue from 'vue'
export default {
  components: {
    OneTableTemplate,
    dialogHeader
  },
  mixins: [oneTableWithViewTemplateMixins],
  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, 'supplierMessage-edit'], () => {
      next()
    })
  },
  props: {
    popupsVisible: {
      type: Boolean,
      default: false
    },
    dataForForm: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      titleName: '订单收款',
      btnText: '收款',
      // 网格查询API配置对象
      apiConfig: orgApis.orderCollectionDealQuery,
      showCodediv: false,
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          clickEvent: () => { this.formField.payType === '1' ? this.showCode() : this.collect() },
          text: '收款',
          name: 'confirm',
          position: 'right',
          fuzzySearch: true
        }
      ],
      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            // 显示组件
            {
              compKey: 'compKey1',
              codeField: 'payType',
              labelName: '支付方式：',
              component: () => import('@/components/org/radioBox/index.vue'),
              type: 'radio',
              isMust: true,
              span: 24,
              options: [
                { value: '1', label: 'POS支付' },
                { value: '2', label: '转账支付' }
              ]
            },
            {
              compKey: 'compKey2',
              labelName: '收款项目：',
              codeField: 'gatheringItemCode',
              disabled: true,
              lookuptype: 'VE1016 ',
              isRequire: true,
              component: () => import('@/components/org/LookupValue'),
              type: 'dropdownList',
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey4',
              labelName: '订单编号：',
              disabled: true,
              isShow: false,
              codeField: 'saleOrderCode',
              component: () => import('@/components/org/commonInput'),
              isMul: false,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey3',
              labelName: '收款金额：',
              disabled: false,
              codeField: 'gatheringAmount',
              isRequire: true,
              component: () => import('@/components/org/commonInput'),
              isMul: false,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey6',
              labelName: '流水号：',
              isShow: false,
              isRequire: true,
              codeField: 'busInessOrderId',
              component: () => import('@/components/org/commonInput'),
              parentFileds: 'show:payType-2-1',
              isMul: false,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey7',
              labelName: '转账时间：',
              isShow: false,
              codeField: 'payTime',
              component: () => import('@/components/org/datePicker/datePicker.vue'),
              dateType: 'date',
              parentFileds: 'show:payType-2-1',
              isRequire: true,
              isMul: false,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey8',
              labelName: '付款人：',
              isShow: false,
              codeField: 'payer',
              component: () => import('@/components/org/commonInput'),
              parentFileds: 'show:payType-2-1',
              isRequire: true,
              isMul: false,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey9',
              labelName: '付款银行名称：',
              isShow: false,
              codeField: 'payBank',
              component: () => import('@/components/org/commonInput'),
              parentFileds: 'show:payType-2-1',
              isRequire: true,
              isMul: false,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey10',
              labelName: '付款银行账号：',
              isShow: false,
              codeField: 'payAccount',
              component: () => import('@/components/org/commonInput'),
              parentFileds: 'show:payType-2-1',
              isRequire: true,
              isMul: false,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey11',
              labelName: '备注：',
              codeField: 'remark',
              isShow: false,
              parentFileds: 'show:payType-2-1',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey12',
              labelName: '已收尾款：',
              codeField: 'factReceivedAmount',
              isShow: true,
              component: () => import('./weikuan'),
              isMust: true,
              span: 9
            },
            {
              compKey: 'compKey13',
              labelName: '应收尾款：',
              codeField: 'gatheringWeiPrice',
              isShow: true,
              component: () => import('./weikuan'),
              isMust: true,
              span: 9
            }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'gatheringItemName',
              label: '收款项目',
              width: null,
              isMul: false,
              align: 'center'
            },
            {
              prop: 'payFlowNo',
              label: '交易流水号', width: 160
            },
            {
              prop: 'gatheringOrderID',
              label: '收款单编号', width: 140
            },
            {
              prop: 'payer',
              label: '付款人', width: 120
            },
            {
              prop: 'gateringDate',
              label: '支付时间', width: 180
            },
            {
              prop: 'gatheringAmount',
              label: '整车金额',
              width: 100
            },
            {
              prop: 'receivedAmount',
              label: '已收总金额',
              width: 100
            },
            {
              prop: 'faceRecervedAmount',
              label: '实收金额',
              width: 100
            },
            {
              prop: 'payTypeName',
              label: '收款方式', width: 120
            },
            {
              prop: 'bankName',
              label: '付款银行名称', width: 120
            },
            {
              prop: 'bankAccount',
              label: '付款银行账号', width: 120
            },
            {
              prop: 'remark',
              label: '备注'
            }
          ],
      orderdata: {
        busInessOrderId: '',
        createTime: '',
        gatheringItemCode: '3',
        remark: '',
        payAccount: '',
        payBank: '',
        payer: '',
        payTime: ''
      },
      dynamicFieldsData: {},
      carConfigCN: '',
      tableKey: 0,
      shuaxin: '',
      formField: {
        payType: '1',
        factReceivedAmount: this.dataForForm.factReceivedAmount,
        gatheringWeiPrice: this.dataForForm.zcwkPrice,
        saleOrderCodeC: this.dataForForm.saleOrderCodeC,
        saleOrderCode: this.dataForForm.saleOrderCode,
        saleOrderId: this.dataForForm.saleOrderId,
        custName: this.dataForForm.custName,
        deliveryDlrId: this.dataForForm.deliveryDlrId,
        empName: this.dataForForm.empName,
        gatheringAmount: this.dataForForm.gateringWeiPrice,
        updateControlIdD: this.dataForForm.updateControlIdD,
        gatheringPrice: this.dataForForm.gatheringPrice,
        receivedAmount: this.dataForForm.receivedAmount
      },
      // 单表格模版页面组件回调事件
      callbackObj: {

      }
    }
  },
  watch: {
    'formField.payType': {
      deep: true,
      handler: function(newV, oldV) {
        this.formField.gatheringAmount = ''
        this.shuaxin = this.$utils.generateId()
        if (newV === '1') {
          this.tableButtons[0].text = '收款'
        } else {
          this.tableButtons[0].text = '保存'
        }
      }
    }
  },
  created() {
    this.formField = Object.assign(this.formField, this.orderdata)
  },
  mounted() {
    this.$nextTick(() => {
      this.queryTableaaa()
    })
  },
  methods: {
    // 详情查询
    queryTableaaa() {
      this.$refs['multipleTable'].listLoading = true
      var queryid = { saleOrderId: this.dataForForm.saleOrderId }
      // // 先读取参数中的传输对象
      const returnObj = {
      // api配置
        apiConfig: orgApis.orderdetailquery,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: queryid
      }
      // 转换了中台请求格式数据
      var paramD = this.$getParams(returnObj, null, this.dynamicApiStyle)
      // 调用中台API方法（可复用）
      this.$requestAPI(paramD, this.dynamicApiStyle).then(response => {
        if (response.result === '0') {
          this.$refs['multipleTable'].listLoading = false
          if (response.msg) {
            this.$message({
              message: response.msg,
              type: 'warn',
              uration: 2000
            })
          }
          return
        }
        // 返回json
        Object.assign(this.dynamicFieldsData, response.rows[0].orderDetails)
        this.carConfigCN = this.dynamicFieldsData.carConfigCN
        var arr1 = response.rows[0].orderCollectionDetails
        for (var i = 0; i < arr1; i++) {
          if (!arr1[i].index) {
            arr1[i].index = i
          }
        }
        this.$refs['multipleTable'].list = arr1
        this.$refs['multipleTable'].pageTotal = arr1.length
        this.$refs['multipleTable'].listLoading = false
        this.tableKey = this.$utils.generateId()
      }).catch(err => {
        console.info(err)
        this.$refs['multipleTable'].listLoading = false
      })
    },
    qrcode(qWidth, qHeight, qText, qRender) {
      const qrcode = new QRCode('qrcode', {
        width: qWidth,
        height: qHeight,
        text: qText,
        render: qRender
      })
    },

    /**
     * @description 点击显示二维码
     */
    showCode() {
      var { saleOrderCodeC, gatheringAmount, custName } = this.formField
      var { saleContractCode } = this.dynamicFieldsData
      var { zcwkPrice } = this.dataForForm
      if (gatheringAmount) {
        if (parseFloat(gatheringAmount) <= zcwkPrice) {
          var codeData =
          `{
            "body":
              [
                {
                  "orderCode": "${saleOrderCodeC}",
                  "amount":"${gatheringAmount}",
                  "custName":"${custName}",
                  "saleContractCode":"${saleContractCode}",
                  "module":"V",
                  "carConfigCN":"${this.carConfigCN}"
                }
              ]
          }
          `
          this.showCodediv = true
          // 二维码初始化 点击一次添加一个二维码
          this.$nextTick(function() {
            this.$refs.qrcode.innerHTML = ''
            this.qrcode(200, 200, codeData, 'canvas')
          })
        } else {
          this.$message({
            message: 'pos付款金额不能大于整车尾款减去已收尾款！',
            duration: 2000
          })
        }
      } else {
        this.$message({
          message: '请输入付款金额！',
          duration: 2000
        })
      }
    },
    // 关闭二维码
    closeCode() {
      this.showCodediv = false
    },
    // 收款
    collect() {
      this.$utils.validataMoth(this, 'validpage', '', 'multipleTable1')
      if (this.valid) {
        var { gatheringAmount } = this.formField
        var { zcwkPrice } = this.dataForForm
        if (parseFloat(gatheringAmount) <= zcwkPrice) {
          this.$refs.multipleTable.listLoading = true
          const that = this
          var api
          // if (this.formField.payType === '1') {
          // api = orgApis.orderCollectionConfirmPOS
          // } else {
          api = orgApis.orderCollectionConfirm
          // }
          const queryObj = {
            // api配置
            apiConfig: api,
            // 条件/实体参数（变量），根据typeParam中的定义配置
            variables: {
              // 当前中台使用的名称有dataInfo、info，具体查看API文档
              dataInfo: this.formField
            }
          }
          // 转换了中台请求格式数据
          var paramD = that.$getParams(queryObj)
          // 调用中台API方法（可复用）
          that.$requestAPI(paramD).then(response => {
            this.$message({
              message: response.msg,
              duration: 2000
            })
            this.$refs.multipleTable.listLoading = false
            if (response.result === '1') {
              this.closeEdit('1')
            }
          })
        } else {
          this.$message({
            message: '转账付款金额不能大于整车尾款减去已收尾款！',
            duration: 2000
          })
        }
      }
    },
    watchComp(isDialog) {
      var that = this
      if (that.hasWatched !== true) {
        that.hasWatched = true
        that.$utils.watchComp(that, isDialog, null, null, null, 'multipleTable1')
        that.$utils.setDisable(that)
      }
    },
    closebtn() {
      this.$parent.close()
    },
    // 关闭弹窗
    closeEdit(type) {
      this.$emit('close', '1')
    },
    // 保存
    save(res) {
    }
  }
}
</script>
<style scoped>
  #qrcode{
    display: inline-block;
    margin:100px 130px
  }
</style>
